package mylibrary.thread.threadpool;

/**
 * Created 5 threads and execute 10 tasks to write files
 * 
 * Log:
 * 		2013-03-04 15:51:55.827 Thread - 4 started
		2013-03-04 15:51:55.826 Thread - 5 started
		2013-03-04 15:51:55.826 Thread - 3 started
		2013-03-04 15:51:55.827 Thread - 1 started
		2013-03-04 15:51:55.824 Thread - 2 started
		2013-03-04 15:52:04.005 Thread - 4 finished
		2013-03-04 15:52:04.006 Thread - 6 started
		2013-03-04 15:52:04.048 Thread - 2 finished
		2013-03-04 15:52:04.048 Thread - 7 started
		2013-03-04 15:52:05.521 Thread - 5 finished
		2013-03-04 15:52:05.522 Thread - 8 started
		2013-03-04 15:52:05.67 Thread - 1 finished
		2013-03-04 15:52:05.67 Thread - 9 started
		2013-03-04 15:52:06.002 Thread - 3 finished
		2013-03-04 15:52:06.002 Thread - 10 started
		2013-03-04 15:52:11.487 Thread - 7 finished
		2013-03-04 15:52:11.516 Thread - 6 finished
		2013-03-04 15:52:13.51 Thread - 9 finished
		2013-03-04 15:52:13.583 Thread - 8 finished
		2013-03-04 15:52:13.673 Thread - 10 finished
 * 
 */
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.sql.Timestamp;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class FixedThreadPoolTest {

	public static void main(String[] args) {
		
		ExecutorService service = Executors.newFixedThreadPool(5);
		
		for(int i=1; i<=10; i++) {
			
			Runnable command = new FixedThreadPoolTest.Command(i);
			service.execute(command);
		}
		
		service.shutdown();
	}
	
	private static class Command implements Runnable {
	
		private int i;
		public Command(int i) {
			this.i = i;
		}
		public void run() {

			try {
				System.out.println(new Timestamp(System.currentTimeMillis()) + " Thread - " + i + " started");
				
				String fileName = "d:\\Test\\" + i + ".txt";
				File file = new File(fileName);
				Writer writer = new FileWriter(fileName);
				
				//10M
				while(file.length()<1024*1000*10) {
					writer.write("This is the test file \n\r");
				}
				
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			System.out.println(new Timestamp(System.currentTimeMillis()) + " Thread - " + i + " finished");
		
		}
	}
}
